﻿using Builder;
using ConfigurationUtility;
using DataModel;
using GlobalUtility;
using LogCentre;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TSC;

namespace TempratureSensorAcquisition
{
    public partial class Form1 : Form
    {
        ConfigUtility configUtility;
        TempratureManager temprature;
        //TaskFactory taskFactory;
        delegate void SetTextCallBack(CheckBox cb,bool text);

        public Form1()
        {
            InitializeComponent();
            //taskFactory = new TaskFactory();
            configUtility = ConfigUtility.ConfigInfo();
            GlobalVar.ConnectionString = configUtility.GetValue(Constant_Fields.SQLConnectionstring);

            Thread t = new Thread(PutState);
            t.Start();
            //MainLog.WriteToGui();
            MainLog.UiLogReceived += Log_UiLogReceived;
            this.Text = "三宁化工2#感温电缆数据采集";
            MainLog.Info("应用程序已启动。");
        }

        private void SetCheckBox(CheckBox cb, bool value)
        {
            if (cb.InvokeRequired)
            {
                SetTextCallBack stcb = new SetTextCallBack(SetCheckBox);
                this.Invoke(stcb, new object[] { cb, value });
            }
            else
            {
                cb.Checked = value;
            }
        }

        private void Temprature_CableDisabledEvent(byte CableId, bool valid)
        {
            string strCtrlName = "chbCable" + CableId;
            Control[] array = this.Controls.Find(strCtrlName, true);

            CheckBox cb = (CheckBox)this.Controls.Find(strCtrlName, true)[0];
            SetCheckBox(cb, valid);
        }

        //private void button2_Click_1(object sender, EventArgs e)
        //{
        //    //tokenSource.Cancel();
        //}

        private void Form1_Load(object sender, EventArgs e)
        {
            foreach (Control control in this.splitContainer2.Panel2.Controls)
            {
                if (control.Name.Contains("chbCable"))
                {
                    //代表是一个使能控件。
                    byte id = Convert.ToByte(control.Name.Substring(8, control.Name.Length - 8));
                    CheckBox cb = (CheckBox)control;
                    TempratureModel gPST = new TempratureModel(id)
                    {
                        IsEnable = true
                    };
                    GlobalVar.tempCache.AddOrUpdate(id, gPST, (key, value) => { return value = gPST; });
                    cb.Checked = true;
                }
            }

            temprature = new TempratureManager(configUtility);
            temprature.CableDisabledEvent += Temprature_CableDisabledEvent;

            StartConnection();
        }

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    StartConnection();
        //}

        private void StartConnection()
        {
            //任意一个有使能的时候，自动建立连接。
            temprature.Start();
        }

        private void chbCable1_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable2_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            byte id = Convert.ToByte(cb.Name.Substring(8, cb.Name.Length - 8));
            bool state = GlobalVar.tempCache[id].IsEnable;
            if (state != cb.Checked)
            {
                //则需要更新GlobalVar.tempCache的数据。
                GlobalVar.tempCache[id].IsEnable = cb.Checked;
                //同时需要更新数据库中的状态。
                GlobalUtils.UpdateCableValidStatus(id, cb.Checked);
            }
        }

        private void chbCable4_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable5_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable6_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable7_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable8_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable9_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable10_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable11_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable12_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable13_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable14_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable15_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable16_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable17_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable18_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable19_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable20_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable21_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable22_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable23_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable24_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable25_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable26_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable27_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable28_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable29_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable30_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable31_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable32_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable33_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable64_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable65_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }

        private void chbCable66_CheckedChanged(object sender, EventArgs e)
        {
            chbCable_CheckedChanged(sender, e);
        }
        private void Log_UiLogReceived(string msg, MessageType type)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (msg.Contains("System.OutOfMemoryException"))
                        {
                            Thread.Sleep(10000);
                            System.Diagnostics.Process.Start(Application.ExecutablePath);
                            Thread.Sleep(100);
                            System.Environment.Exit(0);
                        }
                        else
                        {
                            richTextLog.AppendText(DateTime.Now.ToString("HH:mm:ss") + " [" + type.ToString() + "] " + msg);
                            richTextLog.AppendText("\r\n");
                            richTextLog.ScrollToCaret();
                        }
                    }));
                }
                else
                {
                    richTextLog.AppendText(DateTime.Now.ToString("HH:mm:ss") + " [" + type.ToString() + "] " + msg);
                    richTextLog.AppendText("\r\n");
                    richTextLog.ScrollToCaret();
                }
            }
            catch (Exception ex)
            {
                MainLog.Error(ex.ToString(), true);
            }
        }

        private void PutState()
        {
            while (true)
            {
                if (treeView1.IsDisposed)
                {
                    break;
                }
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        foreach (KeyValuePair<string, string> s in BuilderStatus.EquipmentState)
                        {
                            if (!treeView1.Nodes[0].Nodes.ContainsKey(s.Key))
                            {
                                treeView1.Nodes[0].Nodes.Add(s.Key, s.Key + s.Value);
                                treeView1.ExpandAll();
                            }
                            else
                            {
                                treeView1.Nodes[0].Nodes[s.Key].Text = s.Key + s.Value;
                            }
                        }
                    }));
                }

                Thread.Sleep(5000);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("确定退出系统？", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                try
                {
                    temprature.Stop();
                }
                catch (Exception ex)
                {
                    MainLog.Error(ex);
                }
                System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }

            //DialogResult dr = MessageBox.Show("你确bai定要关闭此窗体么？", "关闭提du示zhi", MessageBoxButtons.YesNo, MessageBoxIcon.Information);//触发事件进行提dao示
            //if (dr == DialogResult.No)
            //{
            //    e.Cancel = true;//就不退了
            //}
            //else
            //{
            //    e.Cancel = false;//退了
            //}
        }

        //private void richTextLog_TextChanged(object sender, EventArgs e)
        //{
        //    List<string> TempLi = new List<string>();
        //    if (richTextLog.Lines.Length > 20)
        //    {
        //        TempLi.AddRange(richTextLog.Lines);
        //        richTextLog.Lines = TempLi.GetRange(richTextLog.Lines.Length - 20, 20).ToArray();
        //        richTextLog.Select(richTextLog.Text.Length - 1, 0);
        //        TempLi.Clear();
        //    }
        //    //GC.Collect();
        //}

        ///// <summary>
        ///// 打开全部
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void button3_Click(object sender, EventArgs e)
        //{
        //    foreach (Control control in this.splitContainer2.Panel2.Controls)
        //    {
        //        if (control.Name.Contains("chbCable"))
        //        {
        //            CheckBox cb = (CheckBox)control;
        //            cb.Checked = true;
        //        }
        //    }
        //}
    }
}
